package com.sky.web.admin;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/report")
public class ReportController {

    @Autowired
    private ReportService reportService;



    // 根据订单状态和指定日期范围内 的 营业额统计
    @GetMapping("/turnoverStatistics")
    public Result turnoverStatistics(
             @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
             @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {//1 接收参数 并处理日期格式

        // 2 调用Service
        TurnoverReportVO turnoverReportVO = reportService.turnoverStatistics(begin,end);
        return Result.success(turnoverReportVO);

    }


    // 根据指定日期范围查询  统计用户数量
    @GetMapping("/userStatistics")
    public Result userStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {

        UserReportVO userReportVO = reportService.userStatistics(begin, end);
        return Result.success(userReportVO);
    }

    // 根据订单状态和指定的日期  统计订单数量
    @GetMapping("/ordersStatistics")
    public Result ordersStatistics(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                                   @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end ){

        // 调用service
        OrderReportVO orderReportVO = reportService.ordersStatistics(begin,end);
        return Result.success(orderReportVO);

    }

    //查询销量排名top10
    @GetMapping("/top10")
    public Result top10(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
        SalesTop10ReportVO vo = reportService.top10(begin, end);
        return Result.success(vo);
    }


    //报表导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //BusinessDataVO   List<BusinessDataVO>
        //1. 构建日期列表
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        List<LocalDate> dateList = getDateList(begin, end);

        //2. 准备变量
        List<BusinessDataVO> list = new ArrayList<>(); //明细列表
        double turnover = 0;//营业额
        double orderCompletionRate = 0;//订单完成率
        int newUsers = 0;//新增用户数
        int validOrderCount = 0;//有效订单数
        double unitPrice = 0;//平均客单价
        int total = 0; //总记录数


        //3. 遍历查询每天的数据
        for (LocalDate date : dateList) {
            BusinessDataVO businessDataVO = reportService.getBusinessData(date);
            businessDataVO.setDate(date);
            list.add(businessDataVO);

            //统计加和
            turnover += businessDataVO.getTurnover();
            orderCompletionRate += businessDataVO.getOrderCompletionRate();//?
            newUsers += businessDataVO.getNewUsers();
            validOrderCount += businessDataVO.getValidOrderCount();
            unitPrice += businessDataVO.getUnitPrice();//?
        }

        //对完成率和客单价做处理
        orderCompletionRate = orderCompletionRate / 30;
        unitPrice = unitPrice / 30;

        //4. 构建BusinessDataVO对象
        BusinessDataVO businessDataVO = BusinessDataVO.builder()
                .beginTime(begin)
                .endTime(end)
                .turnover(turnover)
                .orderCompletionRate(orderCompletionRate)
                .newUsers(newUsers)
                .validOrderCount(validOrderCount)
                .unitPrice(unitPrice)
                .total(list.size())
                .build();

        //5. 填充报表
        //5-1 获取模板文件
        File templateFileName = new ClassPathResource("template/运营数据报表模板.xlsx").getFile();

        //5-2 填充
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            //填充list集合
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);

            //填充对象
            excelWriter.fill(businessDataVO, writeSheet);
        }
    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate dateIndex = begin;//日期指针

        while (!dateIndex.isAfter(end)) {
            dateList.add(dateIndex);
            dateIndex = dateIndex.plusDays(1);//指针后移1天
        }

        return dateList;
    }



}
